package com.baizhiedu.basic.interceptor;

import com.baizhiedu.basic.anno.CreatedOnFuncation;
import com.baizhiedu.basic.anno.UpdatedOnFuncation;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Properties;

/**
 * 时间拦截器.
 */
@EqualsAndHashCode()
@Data
@Accessors(chain = true) // 自动生成setter方法并将setter方法的返回值设置为对象，替换默认的void返回值
@Intercepts({@Signature(
        type = org.apache.ibatis.executor.Executor.class,
        method = "update",
        //为了避免方法重载影响，要指定type#method参数，例如这里args就是Executor#update方法的参数列表
        args = {MappedStatement.class, Object.class})})
public class CreateUpdateTimeInterceptor implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];

        // 获取 SQL 命令
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        // 获取参数
        Object parameter = invocation.getArgs()[1];

        // 获取私有成员变量
        Field[] declaredFields = parameter.getClass().getDeclaredFields();
        if (parameter.getClass().getSuperclass() != null) {
            Field[] superField = parameter.getClass().getSuperclass().getDeclaredFields();
            declaredFields = ArrayUtils.addAll(declaredFields, superField);
        }

        for (Field field : declaredFields) {

            // insert
            if (field.getAnnotation(CreatedOnFuncation.class) != null) {
                if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                    System.out.println("CreatedOnFuncation annotation: " + mappedStatement.getBoundSql(invocation.getTarget()));
                }
            }

            // update
            if (field.getAnnotation(UpdatedOnFuncation.class) != null) {
                if (SqlCommandType.INSERT.equals(sqlCommandType)
                        || SqlCommandType.UPDATE.equals(sqlCommandType)) {
                    field.setAccessible(true);
                    field.set(parameter, LocalDateTime.now());
                    System.out.println("UpdatedOnFuncation annotation: " + mappedStatement.getBoundSql(invocation.getTarget()).getSql());
                }
            }
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        //return target instanceof StatementHandler ? Plugin.wrap(target, this) : target;
        if (target instanceof org.apache.ibatis.executor.Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties prop) {
        this.properties = prop;
    }
}